//
//  HMUserAccountViewModel.m
//  HMWeiBoOC
//
//  Created by GD on 16/9/22.
//  Copyright © 2016年 geduo. All rights reserved.
//

#import "HMUserAccountViewModel.h"
#import "HMUserAccount.h"
#import "HMNetworkTools.h"

@interface HMUserAccountViewModel ()
    
//@property (nonatomic,strong) HMUserAccount *userAccount;

@end

@implementation HMUserAccountViewModel
    
-(HMUserAccount *)userAccount{
    return [HMUserAccount loadUserAccount];
}
    
-(BOOL)isLogin{
    return self.accessToken != nil;
}
    
-(NSString *)accessToken{
    NSString *token = self.userAccount.access_token;
    
    NSDate *now = [NSDate date];
    NSDate *espiresDate = [now dateByAddingTimeInterval:self.userAccount.expires_in];
    
    if ([now compare:espiresDate] == NSOrderedAscending) {
        return self.userAccount.access_token;
    }else{
        return nil;
    }
    return nil;
}

+(instancetype)sharedViewModel{
    
    static HMUserAccountViewModel *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    
    return instance;
}
    
-(void)requestAccessToken:(NSString *)code callBack:(void (^)(BOOL))callback {
    [[HMNetworkTools sharedTools] requestAccessTokenWithCode:code andCallBack:^(id result, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            callback(NO);
        }
        NSLog(@"result===%@",result);
        //转模型
        HMUserAccount *userAccount = [HMUserAccount userAccountWithDict:result];
        [self requestUserInfo:userAccount callBack:callback];
    }];
}
    
-(void)requestUserInfo:(HMUserAccount *)userAccount callBack:(void (^)(BOOL))callback{
    [[HMNetworkTools sharedTools] requestUserInfoWithAccessToken:userAccount.access_token uid:userAccount.uid andCallBack:^(NSDictionary * result, NSError *error) {
        if (error != nil) {
            NSLog(@"网络请求异常: %@",error);
            callback(NO);
            return;
        }
        
        NSString * name = result[@"name"];
        NSString * profile_image_url = result[@"avatar_large"];
        
        userAccount.name = name;
        userAccount.profile_image_url = profile_image_url;
        
        //nsl
        NSLog(@"到此,%@表示用户登录成功",name);
        
        //持久化
        [userAccount saveUserAccount];
        
        callback(YES);
    }];
}

@end
